﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Commerce.Data;

namespace Commerce.CSK.Web.Controls
{
    public partial class CartView : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = 0; 
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            bool hasItems = (CurrentOrder.Items.Count > 0);
            if (hasItems)
            {
                this.cartViewRepeater.DataSource = this.CurrentOrder.Items;
                this.cartViewRepeater.DataBind();
            }
            cartViewRepeater.Visible = hasItems; 
            emptyCartMessage.Visible = !hasItems; 
        }

        public Order CurrentOrder { get; set; }
        

        protected void cartItemCommand(object source, RepeaterCommandEventArgs e)
        {

            switch (e.CommandName)
            {
                case "remove":
                    int productId = 0;
                    if (int.TryParse(e.CommandArgument.ToString(), out productId))
                    {
                        //Product ID is an integer. 
                        CurrentOrder.RemoveItem(productId);
                        SaveCurrentOrder();
                    }
                    break;
            }
            
        }

        private void SaveCurrentOrder()
        {
            Services.GetOrderService().SaveOrder(CurrentOrder);
            Services.GetOrderService().SaveItems(CurrentOrder);
        }
        protected void quantityChanged(object source, EventArgs e)
        {
            TextBox src = source as TextBox;
            int newQty;
            
            if (src != null)
            {
                if (!int.TryParse(src.Text, out newQty))
                {
                    return;
                }
                //The "RemoveItem" ImageButton already has the item id. 
                ImageButton btn = src.Parent.FindControl("removeItem") as ImageButton;
                if (btn != null)
                {
                    int productId = -1;
                    if (int.TryParse(btn.CommandArgument, out productId))
                    {
                        //change the quantity. 
                        CurrentOrder.AdjustQuantity(CurrentOrder.FindItem(productId).Product, newQty);
                        SaveCurrentOrder(); 
                    }
                }
            }
        }
    }
}